//
//  BKPlayerView.m
//  XPhoto
//
//  Created by sentinel on 2020/3/23.
//  Copyright © 2020 baboy. All rights reserved.
//

#import "BKPlayerView.h"
#import <CoreMedia/CoreMedia.h>
#import <BKKit/UIImageView+cache.h>
#import <AFNetworking/UIImageView+AFNetworking.h>
#import <BKKit/NSDate+x.h>

typedef NS_ENUM(NSInteger, BKPlayerStatus) {
    BKPlayerStatusUnInit          = 0,
    BKPlayerStatusPlay     = 1,
    BKPlayerStatusPause,
    BKPlayerStatusFailed,
    BKPlayerStatusFinished
};

@interface BKPlayerView()
@property(nonatomic, assign) id progressObserver;
@property(nonatomic, assign) BKPlayerStatus status;
@end

@implementation BKPlayerView
+ (Class) layerClass{
    return [AVPlayerLayer class];
}
- (void)dealloc{
    [self removePlayerItemObserver:self.playerItem];
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    [_player removeTimeObserver:_progressObserver];
}
- (void)awakeFromNib{
    [super awakeFromNib];
    self.shouldAutoPlay = YES;
    self.showControls = NO;
}
- (void)setShowControls:(BOOL)showControls{
    _showControls = showControls;
    self.controlView.hidden = !showControls;
}
- (void)setShouldAutoPlay:(BOOL)shouldAutoPlay{
    _shouldAutoPlay = shouldAutoPlay;
    self.bigPlayButton.hidden = shouldAutoPlay;
}
- (void)setCoverImage:(UIImage *)coverImage{
    _coverImage = coverImage;
    [self.coverImageView setImage:coverImage];
}
- (void)setCoverURL:(NSURL *)coverURL{
    _coverURL = coverURL;
    [self.coverImageView setImageWithURL:coverURL placeholderImage:nil];
}
- (void)addPlayerItemObserver:(AVPlayerItem *)playerItem{
    // 监听status属性
    [playerItem addObserver:self forKeyPath:@"status" options:NSKeyValueObservingOptionNew context:nil];
    // 监听loadedTimeRanges属性
    [playerItem addObserver:self forKeyPath:@"loadedTimeRanges" options:NSKeyValueObservingOptionNew context:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(playItemDidPlayToEnd:) name:AVPlayerItemDidPlayToEndTimeNotification object:playerItem];
}

- (void)removePlayerItemObserver:(AVPlayerItem *)playerItem{
    // 监听status属性
    [playerItem removeObserver:self forKeyPath:@"status"];
    // 监听loadedTimeRanges属性
    [playerItem removeObserver:self forKeyPath:@"loadedTimeRanges"];
    
    [[NSNotificationCenter defaultCenter] removeObserver:self name:AVPlayerItemDidPlayToEndTimeNotification object:playerItem];
}
- (void)addPlayerObserver{
    
    __weak typeof(self)WeakSelf = self;
    self.progressObserver = [self.player addPeriodicTimeObserverForInterval:CMTimeMakeWithSeconds(1, NSEC_PER_SEC)
                                              queue:NULL
                                         usingBlock:^(CMTime time) {
        //进度 当前时间/总时间
        CGFloat progress = CMTimeGetSeconds(WeakSelf.player.currentItem.currentTime) / CMTimeGetSeconds(WeakSelf.player.currentItem.duration);
        WeakSelf.progressView.progress = progress;
        [WeakSelf updateDisplay];
        //在这里截取播放进度并处理
        if (progress == 1.0f) {
//            [WeakSelf stop];
        }
        
    }];
}
- (AVPlayer *)player{
    if (!_player) {
        _player = [[AVPlayer alloc] init];
        [(AVPlayerLayer*)self.layer setPlayer:_player];
        [(AVPlayerLayer*)self.layer setVideoGravity:AVLayerVideoGravityResizeAspectFill];
        [self addPlayerObserver];
    }
    return _player;
}

- (void)setPlayerItem:(AVPlayerItem *)playerItem{
    if( _playerItem != nil ){
        [self removePlayerItemObserver: _playerItem];
    }
    [self addPlayerItemObserver: playerItem];
    _playerItem = playerItem;
    [self.player replaceCurrentItemWithPlayerItem:playerItem];
}
- (void)setVideoURL:(NSURL *)videoURL{
    _videoURL = videoURL;
    AVPlayerItem *playerItem = [[AVPlayerItem alloc] initWithURL:videoURL];
    [self setPlayerItem:playerItem];
}
- (void)setVideoURLAsset:(AVURLAsset *)videoURLAsset{
    
    _videoURLAsset = videoURLAsset;
    _videoURL = videoURLAsset.URL;
    AVPlayerItem *playerItem = [[AVPlayerItem alloc] initWithAsset:videoURLAsset];
    [self setPlayerItem:playerItem];
}
- (void)seekToTime:(CGFloat)t{
    [self.player seekToTime:kCMTimeZero];
}
- (void)setStatus:(BKPlayerStatus)status{
    _status = status;
    DLOG(@"status:%ld", status);
    switch (status) {
            //可以播放
        case BKPlayerStatusUnInit:
        case BKPlayerStatusFinished:
            if (self.playMode == BKPlayerPlayModeDefault){
                [self.playButton setImage:[UIImage imageNamed:@"image"] forState:UIControlStateNormal];
                if (!self.shouldAutoPlay) {
                    self.bigPlayButton.hidden = NO;
                    self.coverView.hidden = NO;
                    self.controlView.hidden = YES;
                }
            }
            break;
            //可以暂停
        case BKPlayerStatusPlay:
            [self.playButton setImage:[UIImage imageNamed:@"image"] forState:UIControlStateNormal];
            self.coverView.hidden = YES;
            self.bigPlayButton.hidden = YES;
            if (self.showControls) {
                self.controlView.hidden = NO;
            }
            break;
            //可以播放
        case BKPlayerStatusFailed:
            [self.playButton setImage:[UIImage imageNamed:@"image"] forState:UIControlStateNormal];
            self.bigPlayButton.hidden = NO;
            self.coverView.hidden = NO;
            break;
            //可以播放
        case BKPlayerStatusPause:
            [self.playButton setImage:[UIImage imageNamed:@"image"] forState:UIControlStateNormal];
            break;
            
        default:
            break;
    }
}
- (void)updateDisplay{
    CGFloat currentTime = CMTimeGetSeconds(self.player.currentItem.currentTime);
    NSString *s = [[NSDate dateWithTimeIntervalSince1970:currentTime] format:@"mm:ss"];
    NSString *e = [[NSDate dateWithTimeIntervalSince1970:self.duration] format:@"mm:ss"];
    self.timeLabel.text = [NSString stringWithFormat:@"%@/%@", s, e];
}
- (void) observeValueForKeyPath:(NSString *)keyPath
                       ofObject:(id)object
                         change:(NSDictionary<NSKeyValueChangeKey,id> *)change
                        context:(void *)context{
    AVPlayerItem *playerItem = (AVPlayerItem *)object;
    if ([keyPath isEqualToString:@"status"]) {
        DLOG(@"playerItem|status:%ld", [playerItem status]);
        AVPlayerStatus status = [[change objectForKey:@"new"] intValue];
        switch (status) {
            case AVPlayerStatusReadyToPlay:{
                CGFloat totalSecond = playerItem.duration.value / playerItem.duration.timescale;//
                self.duration = totalSecond;
                if (self.shouldAutoPlay) {
                    [self play];
                    
                }
                break;
            }
            case AVPlayerStatusFailed:{
                DLOG(@"playerItem|status:%ld,error:%@,asset: %@", [playerItem status], [playerItem error], [playerItem asset]);
                self.coverView.hidden = NO;
                self.bigPlayButton.hidden = NO;
                break;
            }
            default:
                break;
        }
    } else if ([keyPath isEqualToString:@"loadedTimeRanges"]) {
        //获取视频缓冲进度数组，这些缓冲的数组可能不是连续的
        NSArray *loadedTimeRanges = playerItem.loadedTimeRanges;
        //获取最新的缓冲区间
        CMTimeRange timeRange = [loadedTimeRanges.firstObject CMTimeRangeValue];
        //缓冲区间的开始的时间
        NSTimeInterval loadStartSeconds = CMTimeGetSeconds(timeRange.start);
        //缓冲区间的时长
        NSTimeInterval loadDurationSeconds = CMTimeGetSeconds(timeRange.duration);
        //当前视频缓冲时间总长度
        NSTimeInterval currentLoadTotalTime = loadStartSeconds + loadDurationSeconds;
    }
}
- (void)playItemDidPlayToEnd:(NSNotification*)notitication{
    self.status = BKPlayerStatusFinished;
    [self seekToTime:0];
    if (self.playMode == BKPlayerPlayModeSingleLoop) {
        [self play];
    }
}

- (void)play{
    if (self.player && self.videoURL) {
        [self.player play];
        [self.playButton setImage:[UIImage imageNamed:@"image"] forState:UIControlStateNormal];
    }
    self.status = BKPlayerStatusPlay;
}
- (void)pause{
    [self.player pause];
    [self.playButton setImage:[UIImage imageNamed:@"image"] forState:UIControlStateNormal];
    self.status = BKPlayerStatusPause;
}
- (void)stop{
    if (self.status != BKPlayerStatusPlay) {
        return;
    }
    [self.player pause];
    [self.playButton setImage:[UIImage imageNamed:@"image"] forState:UIControlStateNormal];
    self.status = BKPlayerStatusPause;
}
- (void)playOrPause{
    if (self.status == BKPlayerStatusPlay) {
        [self pause];
    }else{
        [self play];
    }
}

- (IBAction)playOrPause:(id)sender{
    [self playOrPause];
}
- (IBAction)seekBarValueChanged:(id)sender{
    
}

+ (BKPlayerView*)view{
    BKPlayerView *v = loadViewFromNib([self class], nil);
    return v;
}
/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

@end
